package ES6.demo;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by dong on 2018/4/23.
 */
public class SearchUtils {

    /**
     * 处理过高亮显示的结果
     * @param indexName 在哪个索引里面搜索
     * @param text 搜索的关键词
     * @param querySize 分页大小
     * @param offset 偏移量
     * @param fieldNames 在哪些字段里面搜索
     * @return List<Map<String, Object>> 命中列表
     */
    public static List<Map<String, Object>> searchForList(String indexName, String text, int querySize, int offset, String... fieldNames){

        SearchHits hits = searchForHits(indexName, text, querySize, offset, fieldNames);
        List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
        for (SearchHit hit : hits) {
            //遍历文档的每个字段，高亮显示处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            Map<String, Object> source = hit.getSourceAsMap();
            //处理高亮 获取高亮字符串
            if (highlightFields != null && highlightFields.size() != 0) {
                String[] needHighLightFields = fieldNames;
                for (String needHighLightField : needHighLightFields) {
                    HighlightField titleField = highlightFields.get(needHighLightField);
                    if (titleField != null) {
                        Text[] fragments = titleField.fragments();
                        if (fragments != null && fragments.length != 0) {
                            StringBuilder name = new StringBuilder();
                            for (Text fragment : fragments) {
                                name.append(fragment);
                            }
                            source.put(needHighLightField, name.toString());
                            //highLights.add(needHighLightField + ":" + name.toString());
                        }
                    }
                }
            }

            res.add(source);
        }

        return res;
    }


    /**
     * 搜索得到命中列表
     * @param indexName 在哪个索引里面搜索
     * @param text 搜索的关键词
     * @param querySize 分页大小
     * @param offset 偏移量
     * @param fieldNames 在哪些字段里面搜索
     * @return SearchHits 命中列表
     */
    public static SearchHits searchForHits(String indexName, String text, int querySize, int offset, String... fieldNames){
        TransportClient client = ESUtils.getClient();
        //构造查询对象
//        QueryBuilder query = QueryBuilders.multiMatchQuery(text, fieldNames);//.analyzer("ik_max_word");
        QueryBuilder query = QueryBuilders.multiMatchQuery(text, fieldNames);//.analyzer("ik_max_word");

        HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
        highlightBuilder.preTags(Constants.PRE_TAGS);
        highlightBuilder.postTags(Constants.LAST_TAGS);

        //搜索结果存入SearchResponse
        SearchResponse response = client.prepareSearch(indexName).highlighter(highlightBuilder)
                .setQuery(query)         //设置查询器

                .setSize(querySize)      //一次查询文档数
                .setFrom(offset)         //设置偏移量
                .get();

        return response.getHits();
    }
}
